#include "include/DelayBufferPool.h"

#using namespace std;

int DelayBufferPool::Init(int num)
{
	if(num <= 0)
	{
		cerr << "error delay buffer number: " << num << endl;
		return 1;
	}

	for(int i = 0; i < num; i++)
	{
		char *buffer = new char[MAX_PACKAGE_SIZE];
		if(NULL == buffer)
		{
			cerr << "can not get mem when num is: " << i << endl;
			return 1;
		}

		_buffer_list.push_front(buffer);
	}

	_max_num = num;

	return 0;
}

void *DelayBufferPool::GetBuffer()
{
	char *buffer = NULL;

	if(0 == _buffer_list.size())
	{
		cout << "delay buffer pool is empty, need get new buffer" << endl;

		buffer = new char[MAX_PACKAGE_SIZE];
	}
	else
	{
		buffer = _buffer_list.front();
		_buffer_list.pop_front();
	}

	return buffer;
}

void DelayBufferPool::ReleaseBuffer(char *buffer)
{
	if(_buffer_list.size() >= _max_num)
	{
		delete [] buffer;
	}
	else
	{
		_buffer_list.push_front(buffer);
	}
}
